import {
    request,
    upload
} from '@/common/service/request'
import cache from '@/common/utils/cache'
import setter from '@/config.js';
import {
    compressImages,
	sha1,
	randString
} from '@/common/utils/util.js';
export default {
    data() {
        return {
            total: 0, //总页数
            page: 0, //页码
            rows: 6, //每页加载数据量
            loadingType: 'loading', //0加载前 1加载中 2没有更多
            isLoading: false, //刷新数据
            loaded: false, //加载完毕
            isSubmit: false, //是否正在提交数据
            share: {}, //分享内容
            itemDataKey: "navigateToItemData",
            //页面数据是否改变
            isChanged: false
        }
    },
    methods: {
		/**
		 * 自定义方法，获取网易云信用户的ACCID和TOKEN
		*/
		$getYX(accid,name){
			let appkey = "809d759e0cda5c8d7fe1d7a75ee022d6";
			let appsecret = "9163d3db4bf6";
			const [Nonce, CurTime] = [randString(20), new Date().getTime().toString().slice(0, 10)]
			const myCheckSum = sha1(appsecret+Nonce+CurTime)
			let headers = {
			    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
			    'AppKey': appkey,
				'Nonce':Nonce,
				'CurTime':CurTime,
				'CheckSum':myCheckSum
			};
			uni.request({
			    url: "https://api.netease.im/nimserver/user/create.action",
			    method: "post",
			    data: {
					accid:accid,
					name:name
				},
			    header: headers,
				
			    success: res => {
			        console.log(res) //{"code":200,"info":{"name":"","accid":"123456789","token":"100bb0199afe1c9d23fb16afe5e3a5f1"}}
			    },
			    fail: res => {
			        //错误提示框
			       console.log(res)//{code: 414, desc: "already register"}
			    }
			})
		},
		
        log() {
            console.log(arguments)
        },
        //监听image加载完成
        imageOnLoad(data, index) {
            if (typeof(data) == "string") {
                this.$set(this[data][index], 'loaded', true);
            } else {
                this.$set(data, 'loaded', true);
            }
        },
        //监听image加载失败
        imageOnError(data, key, index) {
            if (typeof(data) == "string") {
                this[data][index][key] = '/static/images/errorImage.jpg';
            } else {
                this.$set(data, key, true);
            }
        },
        navTo(url, options = {}, append = false) {
            this.$util.throttle(() => {
                //跳转重置当前操作
                this.$finishSubmit();
                if (!url) {
                    return;
                }
                if (options.login && !this.$store.getters.hasLogin) {
                    this.navToLogin();
                    return;
                }
                if (options.data) {
                    if (append == true) {
                        var cdata = cache.get(this.itemDataKey);
                        for (var p in options.data) {
                            cdata[p] = options.data[p];
                        }
                        cache.put(this.itemDataKey, cdata);
                    } else {
                        cache.put(this.itemDataKey, options.data);
                    }
                }
                uni.navigateTo({
                    url
                })
            }, 100);
        },
        switchTab(url, options = {}) {
            this.$util.throttle(() => {
                //跳转重置当前操作
                this.$finishSubmit();
                if (!url) {
                    return;
                }
                if (options.login && !this.$store.getters.hasLogin) {
                    this.navToLogin();
                    return;
                }
                if (options.data) {
                    cache.put(this.itemDataKey, options.data);
                }
                uni.switchTab({
                    url
                })
            }, 100);
        },
        /**
         * navBack 返回
         * @param {Function} 返回成功后执行方法
         * 如果是刷新前一个页面方法可以通过，this.$utils.prePage().initData()执行刷新
         */
        navBack(fn) {
            this.$util.throttle(() => {
                uni.navigateBack({})
                if (fn) {
                    fn();
                }
            }, 200)
        },
        /**
         * navToLoad 将当前页面的方法暴露给打开的页面，让打开的页面执行。
         * @param {String}否设置到data数据中
         * 子页面中通过this.getOpenerEventChannel().emit('refreshData');执行
         */
        navToLoad(url, options = {}) {
            uni.navigateTo({
                url,
                events: {
                    refreshData: (e) => {
                        this.page = 1;
                        this.loadData(e);
                    },
                    deleteItem: (e) => {
                        this.removeItem(e);
                    },
                    update: (e) => {
                        if (this['update'] instanceof Function) {
                            this.update(e)
                        }
                    }
                },
                success: function(res) {
                    if (options.data) {
                        res.eventChannel.emit('acceptDataFromOpenerPage', options.data)
                    }
                }
            })
        },
        /**
         * 获取上一个页面传过来的数据,对象是最好的，不要来数组
         * @param {Boolean} isAutoSet 是否设置到data数据中
         */
        getItemData(isAutoSet) {
            let data = cache.get(this.itemDataKey);
            if (isAutoSet && data) {
                //数组不允许设置
                if (typeof(data) == "array") {
                    return data;
                }
                for (let key in data) {
                    this[key] = data[key];
                }
            }
            return data;
        },
		
		
        /**
         * $request云函数请求
         * @param {String} module
         * @param {String} operation
         * @param {Boolean} data 请求参数
         * @param {Boolean} ext 附加参数
         * @param {Boolean} ext.showLoading 是否显示loading状态，默认不显示
         * @param {Boolean} ext.hideLoading 是否关闭loading状态，默认关闭
         * @param {Boolean} ext.setLoaded 加载完成是设置页面加载完毕
         */
        $request(module, operation, data = {}, ext = {}) {
            return new Promise((resolve, reject) => {
                request(module, operation, data, ext).then(result => {
                    if (ext.hideLoading !== false) {
                        this.isLoading = false;
                    }
                    setTimeout(() => {
                        if (ext && ext.hasOwnProperty('ext') && ext.setLoaded === true) {
                            this.loaded = true;
                            console.log('reqesdf load')
                        }
                    }, 100)
                    resolve(result);
                }).catch((err) => {
                    reject(err);
                })
            })
        },
        /**
         * $upload上传文件请求
         * @param {File} files
         * @param {String} category
         * @param {Boolean} data 请求参数
         */
        $upload(module, operation, files, category, data = {}, ext = {}) {
            return new Promise(async (resolve, reject) => {
                let fileary = [];
                if (files instanceof Array) {
                    fileary = [...files];
                } else {
                    fileary.push(files);
                }
                // let compressResult = await compressImages(fileary);
                // console.error('compressResult:',compressResult)
                upload(module, operation, files, {
                    kind: category,
                    ...data
                }).then(result => {
                    if (ext.hideLoading !== false) {
                        this.isLoading = false;
                    }
                    setTimeout(() => {
                        if (ext && ext.hasOwnProperty('ext') && ext.setLoaded === true) {
                            this.loaded = true;
                            console.log('reqesdf load')
                        }
                    }, 100)
                    resolve(result);
                }).catch((err) => {
                    resolve(err);
                })
            })
        },
        /**
         * navToLoginNotice 登录提示
         */
        navToLoginNotice() {
            // uni.showModal({
            //     title: "温馨提示",
            //     content: '您还未登录，请登录后再操作',
            //     cancelText: '再逛逛',
            //     confirmText: '去登录',
            //     success: (res) => {
            //         if (res.confirm) {
            //             this.navToLogin();
            //         }
            //     }
            // });
        },
        /**
         * navToLogin 跳转到登录页面
         */
        navToLogin() {
            uni.navigateTo({
                url: "/pages/auth/login"
            })
        },
        /**
         * 开始提交数据，设置isSubmit防止重复提交
         * @param {Object} fn
         */
        $submitData(fn) {
            if (this.isSubmit) {
                return false;
            }
            this.isSubmit = true;
            //如果回调不成功，则认为本次执行完毕
            if (!fn()) {
                setTimeout(() => {
                    this.$finishSubmit();
                }, 500)
            }
        },
        /**
         * 结束提交
         */
        $finishSubmit() {
            this.isSubmit = false;
        },
        stopPrevent() {},
        /**
         * 获取分享参数
         * @param {Object} path
         */
        getShareContent(path, query = [], redirect) {
            let imageUrl, title = "",
                userInfo = this.$store.getters.getUserInfo;
            if (userInfo && userInfo.ExtensionAgentId) {
                query.push('u=' + userInfo.ExtensionAgentId);
            } else {
                query.push('u=company');
            }
            if (this.productId) {
                query.push(`productId=${this.productId}`)
            }
            if (redirect) {
                path = '/pages/index/index';
                query.push(`rdt=${redirect}`)
            }
            if (!this.share.title || this.share.title.trim() == "") {
                //读取首页分享
                this.share = '粪肥还田追溯系统';
            }
            if (this.share) {
                if (this.share.pageLinkQuery) {
                    query.push(this.share.pageLinkQuery);
                }
                if (this.share.title) {
                    title = this.share.title;
                }
                //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径。支持PNG及JPG。显示图片长宽比是 5:4。
                if (this.share.imageUrl) {
                    imageUrl = this.share.imageUrl;
                }
            }
            console.log({
                title,
                imageUrl,
                path: path + "?" + query.join('&')
            })
            return {
                title,
                imageUrl,
                query: query.join('&'),
                path: path + "?" + query.join('&')
            };
        },
        getLocation() {
            return new Promise((resolve, reject) => {
                const {
                    longitude,
                    latitude,
                    address,
                    province,
                    city,
                    country,
                    town
                } = this.$store.getters.getLoaction;
                resolve({
                    code: 1,
                    msg: '',
                    data: {
                        longitude: longitude,
                        latitude: latitude,
                        address: address,
                        province: province,
                        city: city,
                        country: country,
                        town: town
                    }
                })
            })
        },
        /**
         * 拨打电话
         */
        callPhone(phoneNumber) {
            uni.makePhoneCall({
                phoneNumber: phoneNumber
            })
        },
        totalMessage() {
            return new Promise((resolve, reject) => {
                this.$request('message', 'list', {
                    page: 1,
                    rows: 10,
                    ReadStatus: 'unread'
                }).then(res => {
                    if (res.code == 1 && res.data.records > 0) {
                        uni.showTabBarRedDot({
                            index: 3
                        });
                        resolve(res.data.records);
                    } else {
                        uni.hideTabBarRedDot({
                            index: 3
                        });
                        resolve(0);
                    }

                }).catch(err => {
                    resolve(0);
                })
            })
        }
    }
}
